// 导入模块
import { _decorator, Component, Vec3, Node } from 'cc';
const { ccclass, property } = _decorator;

/**
 * 玩家相机控制器
 */
@ccclass('CameraController')
export class CameraController extends Component {
    /**
     * 跟随目标（玩家）
     */
    @property(Node)
    public target: Node | null = null;

    /**
     * 跟随速度
     */
    @property
    public followSpeed: number = 5;

    /**
     * 相机距离
     */
    @property
    public distance: number = 5;

    /**
     * 相机高度
     */
    @property
    public height: number = 2;

    private _currentPosition: Vec3 = new Vec3();

    update(deltaTime: number) {
        if (!this.target) return;

        // 计算目标位置(基于玩家前方)
        const targetPos = new Vec3();
        Vec3.transformMat4(targetPos, Vec3.FORWARD, this.target.worldMatrix);
        Vec3.multiplyScalar(targetPos, targetPos, -this.distance);
        Vec3.add(targetPos, targetPos, this.target.position);
        targetPos.y += this.height;

        // 平滑移动
        Vec3.lerp(
            this._currentPosition,
            this.node.position,
            targetPos,
            deltaTime * this.followSpeed,
        );
        this.node.position = this._currentPosition;

        // 始终看向目标
        this.node.lookAt(this.target.position);
    }
}
